﻿using System;
using MugenInjection.Attributes;
using MugenInjection.Core;
using MugenInjection.Exceptions;
using MugenInjection.Interface;
using MugenInjection.Logging.Interface;
using MugenInjection.Logging.Interface.Components;

namespace MugenInjection.Logging.Modules
{
    /// <summary>
    /// Base implementation for logger modules.
    /// </summary>
#if !NOLOADASSEMBLY
    [AutoLoadModuleRequired]
#endif
    public abstract class LoggerModuleBase : InjectorModule
    {
        #region Overrides of InjectorModule
        
        /// <summary>
        /// Loads bindings and components in current module. 
        /// </summary>
        public override void Load()
        {
            if (Injector.ModuleIsLoaded(Name))
                throw new InvalidSettingException("In the current object is already loaded module to work with the log.");
            Bind<ILogger>().ToMethod(CreateLogger);
        }

        /// <summary>
        /// Gets the module name.
        /// </summary>
        public sealed override string Name
        {
            get { return "~LoggerModuleBase~"; }
        }

        #endregion

        #region Method

        private static ILogger CreateLogger(IBindingContext bindingContext)
        {
            Type loggerType = bindingContext.TypeInto;
            if (loggerType == null)
                throw new ActivatorException(
                    "To create a logger, you must specify the type. You need to pass a parameter using the type of destination.");

            return bindingContext.Injector.Components.Get<ILoggerFactory>().GetLogger(loggerType);
        }

        #endregion
    }
}